package com.dankegongyu.component.jsbridge;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dankegongyu.component.jsbridge.bean.DKWebMenuBean;
import com.dankegongyu.component.jsbridge.bean.DKWebNavigationBean;
import com.dankegongyu.component.jsbridge.config.DKWebConfig;
import com.dankegongyu.component.jsbridge.config.DKWebService;
import com.dankegongyu.component.jsbridge.config.DKWebServiceManager;
import com.dankegongyu.component.jsbridge.config.DKWebToolbarConfig;
import com.dankegongyu.component.jsbridge.jsbridge.CallBackFunction;
import com.dankegongyu.component.jsbridge.listener.DKWebCallback;
import com.dankegongyu.component.jsbridge.listener.DKWebChromeClientCallback;
import com.dankegongyu.component.jsbridge.listener.DKWebSensorsCallback;
import com.dankegongyu.component.jsbridge.listener.DKWebViewMenuCallback;
import com.jaeger.library.StatusBarUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


// 配置测试

/**
 *
 */
public class WebFragment extends Fragment implements View.OnClickListener {

    public static final String SERVICE_KEY = "com.dankegongyu.component.core.webkit.WebFragment";

    private DKWebView mWebView;
    private RelativeLayout mRlBackLayout;
    private ImageView mIvBack;
    private RelativeLayout mRlCloseLayout;
    private ImageView mIvClose;
    private TextView mTvTitle;
    private LinearLayout mToolbarLayout;
    private Toolbar mToolbar;
    private View mBottomLine;

    private DKWebService mService;
    private DKWebConfig mConfig;
    private Map<String, String> mHeaders;
    private String mUrl;

    private String serviceKey;

    private AppCompatActivity mActivity;

    private List<DKWebMenuBean> mMenusFromH5 = new ArrayList<>();
    private RelativeLayout rl_menu;
    private ImageView iv_menu;
    private TextView tv_menu;

    public static WebFragment newInstance(String serviceKey) {
        WebFragment webFragment = new WebFragment();
        Bundle bundle = new Bundle();
        bundle.putString(WebFragment.SERVICE_KEY, serviceKey);
        webFragment.setArguments(bundle);
        return webFragment;
    }

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.jbp_fragment_web, container, false);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mActivity = (AppCompatActivity) getActivity();

        // Init Manage
        init();

        // Handle Business
        doBusiness();

    }

    public void init() {

        setHasOptionsMenu(true);

        initConfig();

        initView();

        initToolbar();

        initData();

    }


    private void initConfig() {

        serviceKey = getArguments().getString(WebFragment.SERVICE_KEY);
        // get config
        mService = DKWebServiceManager.getInstance().get(serviceKey);
        mService.setContext(mActivity);
        mConfig = mService.getConfig();
        if (mConfig == null) {
            mActivity.finish();
        }
    }

    private void initView() {
        // findview
        View view = getView();
        mWebView = view.findViewById(R.id.web_view);
        mToolbarLayout = view.findViewById(R.id.ll_toolbar);
        mToolbar = view.findViewById(R.id.toolbar);
        mTvTitle = view.findViewById(R.id.tv_title);
        mRlBackLayout = view.findViewById(R.id.rl_back_layout);
        mIvBack = view.findViewById(R.id.iv_back);
        mRlCloseLayout = view.findViewById(R.id.rl_close_layout);
        mIvClose = view.findViewById(R.id.iv_close);
        mBottomLine = view.findViewById(R.id.bottom_line);
        rl_menu = view.findViewById(R.id.rl_menu);
        iv_menu = view.findViewById(R.id.iv_menu);
        tv_menu = view.findViewById(R.id.tv_menu);
        rl_menu.setOnClickListener(this);
        if (mService != null) {
            mService.setWebview(mWebView);
        }

    }


    private void initToolbar() {
        // toolbar set

        if (mConfig != null && mConfig.getToolbar() != null && mConfig.getToolbar().isToolbarVisible()) {
            mToolbarLayout.setVisibility(View.VISIBLE);

            // toolbar背景色
            DKWebToolbarConfig toolbarConfig = mConfig.getToolbar();
            if (toolbarConfig.getToolbarColorRes() > 0) {
                mToolbarLayout.setBackgroundColor(ContextCompat.getColor(mActivity, toolbarConfig.getToolbarColorRes()));
            }

            // 标题文字
            mToolbar.setTitle("");
            String title = toolbarConfig.getTitle();
            if (TextUtils.isEmpty(title)) {
                mTvTitle.setText("");
            } else {
                mTvTitle.setText(title);
            }

            // 标题大小
            int titleSize = toolbarConfig.getTitleSize();
            if (titleSize > 0) {
                mTvTitle.setTextSize(TypedValue.COMPLEX_UNIT_DIP, titleSize);
            } else {
                mTvTitle.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
            }

            // 标题颜色
            int titleRes = toolbarConfig.getTitleColor();
            if (titleRes > 0) {
                mTvTitle.setTextColor(ContextCompat.getColor(mActivity, titleRes));
            }

            // bottomline
            if (toolbarConfig.isBottomLineVisible()) {
                mBottomLine.setVisibility(View.VISIBLE);
                if (toolbarConfig.getBottomLineDrawableRes() > 0) {
                    mBottomLine.setBackgroundResource(toolbarConfig.getBottomLineDrawableRes());
                }
            } else {
                mBottomLine.setVisibility(View.GONE);
            }

            mActivity.setSupportActionBar(mToolbar);
            // 显示默认返回箭头
            mActivity.getSupportActionBar().setHomeButtonEnabled(false);
            mActivity.getSupportActionBar().setDisplayHomeAsUpEnabled(false);

            // 返回按钮
            if (toolbarConfig.isBackBtnVisible()) {
                mRlBackLayout.setVisibility(View.VISIBLE);
                mIvBack.setVisibility(View.VISIBLE);
                if (toolbarConfig.getBackBtnRes() > 0) {
                    mIvBack.setImageResource(toolbarConfig.getBackBtnRes());
                } else {
                    mIvBack.setVisibility(View.GONE);
                }

                mRlBackLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (onBackPressed()) {
                            return;
                        }
                        mActivity.finish();
                    }
                });
            } else {
                mRlBackLayout.setVisibility(View.GONE);
                mIvBack.setVisibility(View.GONE);
            }

        } else {
            mToolbarLayout.setVisibility(View.GONE);
            mBottomLine.setVisibility(View.GONE);

            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mWebView.getLayoutParams();
            if (params == null) {
                params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            }
            params.setMargins(0, 0, 0, 0);
            mWebView.setLayoutParams(params);

        }


    }

    private void initData() {
        if (mConfig != null) {
            // set context
            mService.setCallback(mCallback);

            // headers
            mHeaders = mConfig.getHeaders();
            if (mHeaders == null) {
                mHeaders = new HashMap<>();
            }

            // url
            mUrl = mConfig.getUrl();

            //打通神策native和h5
            if (mConfig != null) {
                DKWebSensorsCallback callback = mConfig.getSensorsCallback();
                if (callback != null) {
                    callback.onShowUpWebView(mWebView);
                }
            }
            // setting webview
            mWebView.initSettings(mConfig);
        }
    }

    public void doBusiness() {
        loadUrl();
    }

    private void loadUrl() {
        if (!TextUtils.isEmpty(mUrl) && mHeaders != null) {
            mWebView.loadUrl(mUrl, mHeaders);
        } else if (!TextUtils.isEmpty(mUrl)) {
            mWebView.loadUrl(mUrl);
        }
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
//        if (mConfig != null && mConfig.getToolbar() != null) {
//            DKWebViewMenuCallback callback = mConfig.getMenuCallback();
//            if (callback != null) {
//                callback.onCreateOptionsMenu(menu, inflater, mConfig.getToolbar().getMenuRes(), mMenusFromH5);
//            }
//        }
    }


    @Override
    public void onPrepareOptionsMenu(Menu menu) {
//        if (mConfig != null) {
//            DKWebViewMenuCallback callback = mConfig.getMenuCallback();
//            if (callback != null) {
//                callback.onPrepareOptionsMenu(menu, mMenusFromH5);
//            }
//        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        if (mConfig != null) {
//            DKWebViewMenuCallback callback = mConfig.getMenuCallback();
//            if (callback != null && callback.onOptionsItemSelected(item, mMenusFromH5)) {
//                return true;
//            }
//        }
        return super.onOptionsItemSelected(item);
    }

    private boolean isAllowBackByH5 = true;

    public boolean onBackPressed() {
        if (listenClose) {
            handleFinishCall(isAllowBackByH5 && !mWebView.canGoBack(), isAllowBackByH5 && mWebView.canGoBack());
            return true;
        }

        if (!isAllowBackByH5) {
            return true;
        }
        if (mWebView.canGoBack()) {
            mWebView.goBack(); // 后退
            return true;
        }
        return false;
    }

    private void handleFinishCall(boolean willClose, boolean willGoBack) {
        if (willClose == willGoBack) {
            return;
        }
        //LoadingDialog.show(mActivity);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("willClose", willClose);
            jsonObject.put("willGoBack", willGoBack);
            mWebView.callHandler(JsBridgeConstants.Router.JS_METHOD_LISTEN_CLOSE, jsonObject.toString(), new CallBackFunction() {
                @Override
                public void onCallBack(String data) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mConfig != null) {
            DKWebChromeClientCallback callback = mConfig.getChromeCallback();
            if (callback != null) {
                callback.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

//    @Override
//    public void onDestroy() {
//        if (mWebView != null) {
//            mWebView.destroy();
//        }
//        if(mWebViewContainer != null){
//            mWebViewContainer.removeAllViews();
//        }
//        DKWebServiceManager.getInstance().clear(serviceKey);
//        super.onDestroy();
//    }

    private boolean listenClose = false;
    /**
     * 逻辑层通知到
     */
    private DKWebCallback mCallback = new DKWebCallback() {

        @Override
        public void setNavigationBar(DKWebNavigationBean data) {

            if (data != null) {

                if (data.isToolbarVisible()) {
                    listenClose = data.isListenClose();
                    mToolbarLayout.setVisibility(View.VISIBLE);
                    if (!TextUtils.isEmpty(data.getToolbarTitle())) {
                        mTvTitle.setText(data.getToolbarTitle());
                    }

                    List<DKWebMenuBean> menus = data.getToolbarMenu();
                    refreshMenus(menus);
                    if (mActivity != null && !mActivity.isFinishing()) {
                        getActivity().supportInvalidateOptionsMenu();
                    }
                    if (!TextUtils.isEmpty(data.getToolbarTitleColor())) {
                        try {
                            mTvTitle.setTextColor(Color.parseColor(data.getToolbarTitleColor()));
                        } catch (Exception e) {
                        }
                    }
                    if (mActivity != null && !TextUtils.isEmpty(data.getToolbarColor())) {
                        try {
                            mToolbarLayout.setBackgroundColor(Color.parseColor(data.getToolbarColor()));
                            StatusBarUtil.setColor(mActivity, Color.parseColor(data.getToolbarColor()), 0);
                        } catch (Exception e) {

                        }
                    }
                } else {
                    mToolbarLayout.setVisibility(View.GONE);
                }

            }

        }

        @Override
        public void setNavigationMenus(List<DKWebMenuBean> data) {
            refreshMenus(data);
            if (mActivity != null && !mActivity.isFinishing()) {
                getActivity().supportInvalidateOptionsMenu();
            }
        }

        private void refreshMenus(List<DKWebMenuBean> data) {
            mMenusFromH5.clear();
            rl_menu.setVisibility(View.GONE);
            tv_menu.setVisibility(View.GONE);
            iv_menu.setVisibility(View.GONE);
            tv_menu.setText("");
            if (data != null && data.size() > 0) {
                mMenusFromH5.addAll(data);
                rl_menu.setVisibility(View.VISIBLE);
                if (data.size() == 1) {
                    DKWebMenuBean m = data.get(0);
                    if (m != null && TextUtils.equals(m.getType(), DKWebMenuBean.TYPE_TEXT)) {
                        tv_menu.setVisibility(View.VISIBLE);
                        tv_menu.setText(m.getName());
                    } else {
                        iv_menu.setVisibility(View.VISIBLE);
                    }
                } else {
                    iv_menu.setVisibility(View.VISIBLE);
                }
            }
        }

        @Override
        public void refreshToken(String name, String token) {
            if (mHeaders != null) {
                mHeaders.put(name, token);
            }
        }

        @Override
        public void refreshUrl(String url) {
            mUrl = url;
            loadUrl();
        }

        @Override
        public void refreshCloseBtn(boolean isVisible) {

            if (mConfig != null && mConfig.getToolbar() != null && mConfig.getToolbar().isToolbarVisible()) {

                // 关闭按钮。
                if (mConfig.getToolbar().isCloseBtnVisible() && isVisible) {

                    if (mConfig.getToolbar().getCloseBtnRes() > 0) {

                        mIvClose.setVisibility(View.VISIBLE);
                        mRlCloseLayout.setVisibility(View.VISIBLE);
                        mIvClose.setImageResource(mConfig.getToolbar().getCloseBtnRes());
//                        mRlCloseLayout.setOnClickListener(view -> mActivity.finish());
                        mRlCloseLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (listenClose) {
                                    handleFinishCall(true, false);
                                    return;
                                }
                                if (!isAllowBackByH5) {
                                    return;
                                }
                                mActivity.finish();
                            }
                        });

                    } else {
                        mIvClose.setVisibility(View.GONE);
                        mRlCloseLayout.setVisibility(View.GONE);
                    }

                } else {
                    mRlCloseLayout.setVisibility(View.GONE);
                    mIvClose.setVisibility(View.GONE);
                }

            }


        }

        @Override
        public void allowBack(boolean isAllowBack) {
            isAllowBackByH5 = isAllowBack;
        }

    };


    @Override
    public void onClick(View view) {
        if (R.id.rl_menu == view.getId()) {
            if (mMenusFromH5.size() == 1 && mMenusFromH5.get(0) != null && TextUtils.equals(mMenusFromH5.get(0).getType(), DKWebMenuBean.TYPE_TEXT)) {
                DKWebViewMenuCallback callback = mConfig.getMenuCallback();
                if (callback != null) {
                    callback.onOptionsItemCustomSelected(null, mMenusFromH5.get(0));
                }
            }else {
                showMenuPopup(rl_menu);
            }
        }
    }

    private void showMenuPopup(View view) {
        if (mConfig != null && mConfig.getToolbar() != null) {
            DKWebViewMenuCallback callback = mConfig.getMenuCallback();
            if (callback != null) {
                callback.onCreateOptionsCustomMenu(view, LayoutInflater.from(mActivity), mConfig.getToolbar().getMenuRes(), mMenusFromH5);
            }
        }
    }
}
